<!-- Copyright (c) 2022 渝州大数据实验室
 *
 * Lanius is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 -->
<!-- 
* @desc:资源配置右侧弹出框组件
* @fileName:allocati0n-drawer.vue
* @author:zhouyongjie@yzbdl.ac.cn
* @date:2022-4-6
!-->

<script setup lang="ts">
import { Plus, Delete } from "@element-plus/icons-vue";
import Load from "@/components/common/load.vue";
import { reactive, ref } from "vue";
import { FormInstance } from "element-plus";
import { showErrorMessage, showSuccessMessage } from "@/common/message";
import { getCurrentInstance } from "vue";
import { ConnectUrl } from "@/services/task-schedule/repository";
import { IKeyValue, encryptAes } from "@/services/common/tool";
const { proxy } = getCurrentInstance() as any;

//接收父组件传值
const props = defineProps({
  submitFunc: Function as any,
});
const showLoad = ref(false);
//定义参数
const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
  connectName: "",
  connectCategory: 1,
  connectUrl: new ConnectUrl(),
  connectAccount: "",
  connectPassword: "",
  remark: "",
  status: "" as any,
  paramList: [] as IKeyValue<string, string>[],
});
let options = reactive({
  List: [
    {
      connectCategory: 1,
      value: "MySQL",
    },
    {
      connectCategory: 2,
      value: "Oracle",
    },
  ],
});

const clickConncet = ref(false);
const labelPosition = ref("top");
//定义校验规则
const rules = reactive({
  connectName: [
    { required: true, message: "请输入资源库名称", trigger: "blur" },
    { min: 1, max: 64, message: "长度为1-64位", trigger: "blur" },
  ],
  connectCategory: [
    { required: true, message: "请选择资源库类型", trigger: "blur" },
  ],
  connectAccount: [
    { required: true, message: "请输入连接用户", trigger: "blur" },
  ],
  connectPassword: [
    { required: true, message: "请输入连接密码", trigger: "blur" },
  ],
});

/**
 * @description:提交表单
 * @param {FormInstance} formEl
 * @return void
 */
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      ruleForm.connectUrl.setParams(ruleForm.paramList);
      if (clickConncet.value === false) {
        showLoad.value = true;
        const res = proxy.$HTTP.post({
          url: `/resource/taskResourceConfig/testConnection`,
          data: {
            connectUrl: ruleForm.connectUrl.toString(),
            connectAccount: ruleForm.connectAccount,
            connectPassword: encryptAes(ruleForm.connectPassword),
            connectCategory: ruleForm.connectCategory,
          },
        });
        res.then((res: any) => {
          showLoad.value = false;
          if (res.isOk) {
            if (res.data === true) {
              ruleForm.status = 1;
              showSuccessMessage({
                message: "资源库连接成功！",
              });
            } else {
              ruleForm.status = 0;
              showErrorMessage({
                message: "资源库连接失败！",
              });
            }
            const submitres = proxy.$HTTP.post({
              url: `/resource/taskResourceConfig`,
              data: {
                connectName: ruleForm.connectName,
                connectCategory: ruleForm.connectCategory,
                connectUrl: ruleForm.connectUrl.toString(),
                connectAccount: ruleForm.connectAccount,
                connectPassword: encryptAes(ruleForm.connectPassword),
                remark: ruleForm.remark,
                status: ruleForm.status,
              },
            });
            submitres.then((res: any) => {
              if (res.isOk) {
                console.log("res", res);
                props.submitFunc(ruleForm);
              }
            });
            submitres.catch((error: any) => {
              if (error.data instanceof Array) {
                showErrorMessage({
                  message: error.data[0].errorMsg,
                });
              } else {
                showErrorMessage({
                  message: error.data,
                });
              }
            });
          }
        });
        res.catch((error: any) => {
          showLoad.value = false;
          if (error.data instanceof Array) {
            showErrorMessage({
              message: error.data[0].errorMsg,
            });
          } else {
            showErrorMessage({
              message: error.data,
            });
          }
        });
      } else {
        const submitres = proxy.$HTTP.post({
          url: `/resource/taskResourceConfig`,
          data: {
            connectName: ruleForm.connectName,
            connectCategory: ruleForm.connectCategory,
            connectUrl: ruleForm.connectUrl.toString(),
            connectAccount: ruleForm.connectAccount,
            connectPassword: encryptAes(ruleForm.connectPassword),
            remark: ruleForm.remark,
            status: ruleForm.status,
          },
        });
        submitres.then((res: any) => {
          if (res.isOk) {
            console.log("res", res);
            props.submitFunc(ruleForm);
          }
        });
        submitres.catch((error: any) => {
          if (error.data instanceof Array) {
            showErrorMessage({
              message: error.data[0].errorMsg,
            });
          } else {
            showErrorMessage({
              message: error.data,
            });
          }
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

/**
 * @description:选择下拉框函数
 * @param {any} val
 * @return void
 */
const changeSelect = (val: any) => {
  options.List.map((item: any) => {});
};

/**
 * @description:连接测试
 * @param {FormInstance} formEl
 * @return void
 */
const connect = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      showLoad.value = true;
      ruleForm.connectUrl.setParams(ruleForm.paramList);
      const res = proxy.$HTTP.post({
        url: `/resource/taskResourceConfig/testConnection`,
        data: {
          connectUrl: ruleForm.connectUrl.toString(),
          connectAccount: ruleForm.connectAccount,
          connectPassword: encryptAes(ruleForm.connectPassword),
          connectCategory: ruleForm.connectCategory,
        },
      });
      res.then((res: any) => {
        showLoad.value = false;
        if (res.isOk) {
          clickConncet.value = true;
          if (res.data === true) {
            ruleForm.status = 1;
            showSuccessMessage({
              message: "资源库连接成功！",
            });
          } else {
            ruleForm.status = 0;
            showErrorMessage({
              message: "资源库连接失败！",
            });
          }
        }
      });
      res.catch((error: any) => {
        showLoad.value = false;
        if (error.data instanceof Array) {
          showErrorMessage({
            message: error.data[0].errorMsg,
          });
        } else {
          showErrorMessage({
            message: error.data,
          });
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const onParamPlusClick = () => {
  ruleForm.paramList.push({ key: "", value: "" });
};

const onParamDeleteClick = (param: IKeyValue<string, string>) => {
  let index = ruleForm.paramList.indexOf(param);
  if (index > -1) {
    ruleForm.paramList.splice(index, 1);
  }
};

const validatePort = (rule: any, value: any, callback: any) => {
  if (!ruleForm.connectUrl.port) {
    callback(new Error("请输入端口"));
    return;
  }
  if (ruleForm.connectUrl.port >= 1 && ruleForm.connectUrl.port <= 65535) {
    callback();
  } else {
    callback(new Error("端口范围是1~65535"));
  }
};
</script>

<template>
  <Load v-if="showLoad" />
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="rules"
    :label-position="labelPosition"
    label-width="120px"
    class="demo-ruleForm"
    :size="formSize"
  >
    <el-form-item label="资源库名称" prop="connectName">
      <el-input
        v-model="ruleForm.connectName"
        size="large"
        placeholder="请输入资源库名称"
        show-word-limit
        maxlength="64"
      />
    </el-form-item>
    <el-row :gutter="20">
      <el-col :span="11">
        <el-form-item label="资源库类型" prop="connectCategory">
          <el-select
            size="large"
            v-model="ruleForm.connectCategory"
            @change="changeSelect"
            clearable
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in options.List"
              :key="item.connectCategory"
              :label="item.value"
              :value="item.connectCategory"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="11">
        <el-form-item
          label="数据库IP"
          prop="connectUrl.ip"
          :rules="{
            required: true,
            message: '请输入数据库IP',
            trigger: 'blur',
          }"
        >
          <el-input
            v-model="ruleForm.connectUrl.ip"
            size="large"
            placeholder="请输入数据库IP"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="11">
        <el-form-item
          label="端口"
          prop="connectUrl.port"
          :rules="{
            required: true,
            validator: validatePort,
            trigger: 'blur',
          }"
        >
          <el-input
            v-model="ruleForm.connectUrl.port"
            size="large"
            placeholder="请输入端口"
          />
        </el-form-item>
      </el-col>
      <el-col :span="11">
        <el-form-item
          label="库名"
          prop="connectUrl.dbName"
          :rules="{
            required: true,
            message: '请输入库名',
            trigger: 'blur',
          }"
        >
          <el-input
            v-model="ruleForm.connectUrl.dbName"
            size="large"
            placeholder="请输入库名"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <el-button
      :icon="Plus"
      @click="onParamPlusClick"
      circle
      size="mini"
      class="btn-para-add"
    />
    <el-row
      v-for="(item, index) in ruleForm.paramList"
      :key="index"
      :gutter="20"
    >
      <el-col :span="11">
        <el-form-item
          :prop="'paramList.' + index + '.key'"
          :rules="{
            required: true,
            message: '请输入参数名',
            trigger: 'blur',
          }"
        >
          <el-input
            v-model="item.key"
            size="large"
            placeholder="请输入参数名"
          />
        </el-form-item>
      </el-col>
      <el-col :span="11">
        <el-form-item
          :prop="'paramList.' + index + '.value'"
          :rules="{
            required: true,
            message: '请输入参数值',
            trigger: 'blur',
          }"
        >
          <el-input
            v-model="item.value"
            size="large"
            placeholder="请输入参数值"
          />
        </el-form-item>
      </el-col>
      <el-col :span="2">
        <el-button
          type="danger"
          text
          circle
          :icon="Delete"
          size="large"
          @click="onParamDeleteClick(item)"
        ></el-button>
      </el-col>
    </el-row>
    <el-form-item label="连接用户" prop="connectAccount">
      <el-input
        v-model="ruleForm.connectAccount"
        size="large"
        placeholder="请输入连接用户"
      />
    </el-form-item>
    <el-form-item label="连接密码" prop="connectPassword">
      <el-input
        v-model="ruleForm.connectPassword"
        size="large"
        type="password"
        show-password
        placeholder="请输入连接密码"
      />
    </el-form-item>
    <el-form-item label="备注" prop="remark">
      <el-input
        v-model="ruleForm.remark"
        type="textarea"
        size="large"
        show-word-limit
        maxlength="512"
        placeholder="请输入备注"
      />
    </el-form-item>

    <el-form-item class="ClickButton">
      <el-button @click="connect(ruleFormRef)">连接测试</el-button>
      <el-button @click="submitForm(ruleFormRef)">确定</el-button>
    </el-form-item>
  </el-form>
</template>
<style lang="scss" scoped>
:deep(.el-form-item__label) {
  font-family: PingFang SC;
  font-weight: 700;
  color: #000000;
  font-size: 14px;
}
:deep(.el-input) {
  height: 40px;
  background-color: #ffffff;
}
:deep(.el-textarea) {
  height: 100px;
  background-color: #ffffff;
  .el-textarea__inner {
    height: 100px;
  }
}
.ClickButton {
  :deep(.el-form-item__content) {
    display: flex;
    justify-content: flex-end;
    .el-button {
      height: 40px;
      background-color: #ffffff;
      border: 1px solid;
      border-color: #cccccc;
    }
  }
}

.btn-para-add {
  margin-bottom: 20px;
}
</style>
